package com.jobchecks.ping.service;

import com.alibaba.fastjson.JSON;
import com.jobchecks.common.baseresult.JobchecksResult;
import com.jobchecks.dao.domain.PingRecord;
import com.jobchecks.dao.mapper.PingRecordMapper;
import com.jobchecks.ping.api.TestPingService;
import com.jobchecks.ping.api.request.TestReq;
import com.jobchecks.ping.api.response.TestResp;
import com.jobchecks.ping.exception.PingServiceException;
import com.jobchecks.ping.exception.PingServiceExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * 测试服务实现
 *
 * @author huangjinjia
 */
@Service(version = "1.0.0", timeout = 30000, interfaceClass = TestPingService.class)
@Component
@Slf4j
public class TestPingServiceImpl implements TestPingService {

    @Autowired
    private PingRecordMapper pingRecordMapper;

    @Override
    public JobchecksResult<TestResp> add(TestReq req){
        log.info("testAdd接口开始");
        TestResp testResp = new TestResp();
        testResp.setId(UUID.randomUUID().toString());
        testResp.setNum(req.getAge());
        testResp.setCreateTime(new Date());
        testResp.setLevel(new BigDecimal(5));

        // 测试新增数据
        PingRecord pingRecord = new PingRecord();
        pingRecord.setId(UUID.randomUUID().toString().replace("-", ""));
        pingRecord.setCreateBy("hjj");
        pingRecord.setCreateTime(new Date());
        pingRecord.setCheckItemId(UUID.randomUUID().toString().replace("-", ""));
        pingRecord.setPingIp("11.11.11.112");
        pingRecord.setRequestContent(JSON.toJSON(req).toString());
        // 入库
        pingRecordMapper.insertSelective(pingRecord);

        log.info("testAdd接口结束");
        // 测试主动抛出异常
        if("test".equals(req.getName())){
            throw new PingServiceException(PingServiceExceptionCode.PING_REQUEST_TIMEOUT);
        }
        return JobchecksResult.success(testResp);
    }

    @Override
    public String update(String key, String conf) {
        log.info("testUpdate接口开始");
        log.info("testUpdate接口结束");
        return "测试 /gateway/testUpdate/ 成功，key=" + key;
    }
}
